import { createSSRApp } from "vue";
import * as Pinia from 'pinia';
import tmui from "./tmui"
import App from "./App.vue";

uni.addInterceptor('request', {
	invoke(args) {
		// request 触发前拼接 url 
		args.url = '/api' + args.url;
		let token = uni.getStorageSync("Token");
		args.header = {
			'content-type': 'application/json',
			'Token': token
		}

	},
	returnValue(args) {
		// 只返回 data 字段
		return args.data
	},
	success(args) {
		let code = args.data.code;
		if (code == '504') {
			uni.navigateTo({
				url: '/src/pages/login/login'
			})
		}
	},
	fail(err) {
		console.log("网络异常" + err);
	},

})

// 页面白名单
const whiteList = [
	'/',
	'/pages/login/index',
	'/pages/index/index'
]

function hasPermission(url : string) {
	// 在白名单中或有token，直接跳转
	if (whiteList.indexOf(url) !== -1 || uni.getStorageSync('Token')) {
		return true
	}
	return false
}

uni.addInterceptor('navigateTo', {
	// 页面跳转前进行拦截, invoke根据返回值进行判断是否继续执行跳转
	invoke(e) {
		if (!hasPermission(e.url)) {
			uni.reLaunch({
				url: '/pages/login/login'
			})
			return false
		}
		return true
	},
	success(e) {
		// console.log(e)
	}
})

uni.addInterceptor('switchTab', {
	// tabbar页面跳转前进行拦截
	invoke(e) {
		if (!hasPermission(e.url)) {
			uni.reLaunch({
				url: '/pages/login/login'
			})
			return false
		}
		return true
	},
	success(e) {
		// console.log(e)
	}
})

export function createApp() {
	const app = createSSRApp(App);
	app.use(tmui, { shareDisable: false } as Tmui.tmuiConfig)
	return {
		app,
		Pinia
	};
}